<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Notice
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

function modzzz_notices_import ($sClassPostfix, $aModuleOverwright = array()) {
    global $aModule;
    $a = $aModuleOverwright ? $aModuleOverwright : $aModule;
    if (!$a || $a['uri'] != 'notices') {
        $oMain = BxDolModule::getInstance('BxNoticesModule');
        $a = $oMain->_aModule;
    }
    bx_import ($sClassPostfix, $a) ;
}

bx_import('BxDolPaginate');
bx_import('BxDolAlerts');
bx_import('BxDolTwigModule');

define ('BX_NOTICES_PHOTOS_CAT', 'Notices');
define ('BX_NOTICES_PHOTOS_TAG', 'notices');

define ('BX_NOTICES_VIDEOS_CAT', 'Notices');
define ('BX_NOTICES_VIDEOS_TAG', 'notices');

define ('BX_NOTICES_SOUNDS_CAT', 'Notices');
define ('BX_NOTICES_SOUNDS_TAG', 'notices');

define ('BX_NOTICES_FILES_CAT', 'Notices');
define ('BX_NOTICES_FILES_TAG', 'notices');


/*
 * Notices module
 *
 * This module allow users to create user's notices, 
 * users can rate, comment and discuss notice.
 * Notice can have photos, videos, sounds and files, uploaded
 * by notice's admins.
 *
 * 
 *
 * Profile's Wall:
 * 'add notice' event is displayed in profile's wall
 *
 *
 *
 * Spy:
 * The following qactivity is displayed for content_activity:
 * add - new notice was created
 * change - notice was chaned
 * rate - somebody rated notice
 * commentPost - somebody posted comment in notice
 *
 *
 *
 * Memberships/ACL:
 * notices view notice - BX_NOTICES_VIEW_NOTICE
 * notices browse - BX_NOTICES_BROWSE
 * notices search - BX_NOTICES_SEARCH
 * notices add notice - BX_NOTICES_ADD_NOTICE
 * notices comments delete and edit - BX_NOTICES_COMMENTS_DELETE_AND_EDIT
 * notices edit any notice - BX_NOTICES_EDIT_ANY_NOTICE
 * notices delete any notice - BX_NOTICES_DELETE_ANY_NOTICE
 * notices mark as featured - BX_NOTICES_MARK_AS_FEATURED
 * notices approve notices - BX_NOTICES_APPROVE_NOTICES
 *
 * 
 *
 * Service methods:
 *
 * Homepage block with different notices
 * @see BxNoticesModule::serviceHomepageBlock
 * BxDolService::call('notices', 'homepage_block', array());
 *
 * Profile block with user's notices
 * @see BxNoticesModule::serviceProfileBlock
 * BxDolService::call('notices', 'profile_block', array($iProfileId));
 *

 *
 * Member menu item for notices (for internal usage only)
 * @see BxNoticesModule::serviceGetMemberMenuItem
 * BxDolService::call('notices', 'get_member_menu_item', array());
 *
 *
 *
 * Alerts:
 * Alerts type/unit - 'modzzz_notices'
 * The following alerts are rised
 *
 
 *
 *  add - new notice was added
 *      $iObjectId - notice id
 *      $iSenderId - creator of a notice
 *      $aExtras['Status'] - status of added notice
 *
 *  change - notice's info was changed
 *      $iObjectId - notice id
 *      $iSenderId - editor user id
 *      $aExtras['Status'] - status of changed notice
 *
 *  delete - notice was deleted
 *      $iObjectId - notice id
 *      $iSenderId - deleter user id
 *
 *  mark_as_featured - notice was marked/unmarked as featured
 *      $iObjectId - notice id
 *      $iSenderId - performer id
 *      $aExtras['Featured'] - 1 - if notice was marked as featured and 0 - if notice was removed from featured 
 *
 */
class BxNoticesModule extends BxDolTwigModule {

    var $_oPrivacy;
    var $_aQuickCache = array ();

    function BxNoticesModule(&$aModule) {

        parent::BxDolTwigModule($aModule);        
        $this->_sFilterName = 'modzzz_notices_filter';
        $this->_sPrefix = 'modzzz_notices';

        bx_import ('Privacy', $aModule);
        $this->_oPrivacy = new BxNoticesPrivacy($this);

	    $this->_oConfig->init($this->_oDb);

        $GLOBALS['oBxNoticesModule'] = &$this;
    }
 
    function actionHome () {
        parent::_actionHome(_t('_modzzz_notices_page_title_home'));
    }
 
    function actionComments ($sUri) {
        parent::_actionComments ($sUri, _t('_modzzz_notices_page_title_comments'));
    }
  
    function actionView ($sUri) {
        parent::_actionView ($sUri, _t('_modzzz_notices_msg_pending_approval'));
    }
  
    function actionCalendarTravel ($iYear = '', $iMonth = '') {

 		if($_GET['ajax']=='cal'){ 
			
			$this->_oTemplate->addCss ('main.css');
			echo $this->displayMainCalendarTravel($iYear, $iMonth, _t('_modzzz_notices_page_title_calendar')); 
  			exit;
		} 

        parent::_actionCalendar ($iYear, $iMonth, _t('_modzzz_notices_page_title_calendar'));
    }
 
    function actionCalendarAvailable ($iYear = '', $iMonth = '') {

 		if($_GET['ajax']=='cal'){ 
			
			$this->_oTemplate->addCss ('main.css');
			echo $this->displayMainCalendarAvailable($iYear, $iMonth, _t('_modzzz_notices_page_title_calendar')); 
  			exit;
		} 

        parent::_actionCalendar ($iYear, $iMonth, _t('_modzzz_notices_page_title_calendar'));
    }

    function displayMainCalendarTravel($iYear, $iMonth, $sTitle) {
    
        $this->_oTemplate->pageStart();
 
        bx_import ('CalendarTravel', $this->_aModule);
        $oCalendar = bx_instance ($this->_aModule['class_prefix'] . 'CalendarTravel', array ($iYear, $iMonth, $this->_oDb, $this->_oTemplate, $this->_oConfig));
  
        $aVars = array (
            'bx_repeat:week_names' => $oCalendar->_getWeekNames (),
            'bx_repeat:calendar_row' => $oCalendar->_getCalendar (),
            'month_prev_url' => $oCalendar->getBaseUri () . "{$oCalendar->iPrevYear}/{$oCalendar->iPrevMonth}&ajax=cal",
            'month_prev_name' => _t('_month_prev'),
            'month_prev_icon' => getTemplateIcon('sys_back.png'),
            'month_next_url' => $oCalendar->getBaseUri () . "{$oCalendar->iNextYear}/{$oCalendar->iNextMonth}&ajax=cal",
            'month_next_name' => _t('_month_next'),
            'month_next_icon' => getTemplateIcon('sys_next.png'),
            'month_current' => $oCalendar->getTitle(),
        );
        $sHtml = $this->_oTemplate->parseHtmlByName('travel_calendar', $aVars);
        $sHtml = preg_replace ('#<bx_repeat:events>.*?</bx_repeat:events>#s', '', $sHtml);
        $this->_oTemplate->addCss('calendar.css');
        
		return $sHtml;
    } 
   
    function displayMainCalendarAvailable($iYear, $iMonth, $sTitle) {
    
        $this->_oTemplate->pageStart();
 
        bx_import ('CalendarAvailable', $this->_aModule);
        $oCalendar = bx_instance ($this->_aModule['class_prefix'] . 'CalendarAvailable', array ($iYear, $iMonth, $this->_oDb, $this->_oTemplate, $this->_oConfig));
  
        $aVars = array (
            'bx_repeat:week_names' => $oCalendar->_getWeekNames (),
            'bx_repeat:calendar_row' => $oCalendar->_getCalendar (),
            'month_prev_url' => $oCalendar->getBaseUri () . "{$oCalendar->iPrevYear}/{$oCalendar->iPrevMonth}&ajax=cal",
            'month_prev_name' => _t('_month_prev'),
            'month_prev_icon' => getTemplateIcon('sys_back.png'),
            'month_next_url' => $oCalendar->getBaseUri () . "{$oCalendar->iNextYear}/{$oCalendar->iNextMonth}&ajax=cal",
            'month_next_name' => _t('_month_next'),
            'month_next_icon' => getTemplateIcon('sys_next.png'),
            'month_current' => $oCalendar->getTitle(),
        );
        $sHtml = $this->_oTemplate->parseHtmlByName('available_calendar', $aVars);
        $sHtml = preg_replace ('#<bx_repeat:events>.*?</bx_repeat:events>#s', '', $sHtml);
        $this->_oTemplate->addCss('calendar.css');
        
		return $sHtml;
    } 
   
    function actionSearch ($sKeyword = '', $sCategory = '',  $sCompensation = '', $sCountry = '', $sCity = '', $sStart = '', $sEnd = '') {

        if (!$this->isAllowedSearch()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        if ($sKeyword) 
            $_GET['Keyword'] = $sKeyword;
        if ($sCategory)
            $_GET['Category'] = $sCategory;
        if ($sCompensation)
            $_GET['Compensation'] = $sCompensation;
        if ($sCountry)
            $_GET['Country'] = explode(',', $sCountry); 
		if ($sCity) 
            $_GET['City'] = $sCity;
		if ($sStart) 
            $_GET['Start'] = $sStart;
 		if ($sEnd) 
            $_GET['End'] = $sEnd;
  
        if (is_array($_GET['Country']) && 1 == count($_GET['Country']) && !$_GET['Country'][0]) {
            unset($_GET['Country']);
            unset($sCountry);
        }
  
        if ($sKeyword || $sCategory || $sCompensation || $sCountry || $sCity || $sStart || $sEnd) {
            $_GET['submit_form'] = 1;  
        }
        
        modzzz_notices_import ('FormSearch');
        $oForm = new BxNoticesFormSearch ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
	    if($_GET['Start']) 
			$iStartDate = $oForm->getCleanValue('Start');
	    if($_GET['End']) 
			$iEndDate = $oForm->getCleanValue('End');

            modzzz_notices_import ('SearchResult');
            $o = new BxNoticesSearchResult('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('Compensation'), $oForm->getCleanValue('Country'), $oForm->getCleanValue('City'), $iStartDate, $iEndDate);

            if ($o->isError) {
                $this->_oTemplate->displayPageNotFound ();
                return;
            }

            if ($s = $o->processing()) {
                echo $s;
            } else {
                $this->_oTemplate->displayNoData ();
                return;
            }

            $this->isAllowedSearch(true); // perform search action 

            $this->_oTemplate->addCss ('unit.css');
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($o->aCurrent['title'], false, false);
            return;

        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_modzzz_notices_page_title_search'));
    }
  
    function actionAdd () {
        parent::_actionAdd (_t('_modzzz_notices_page_title_add'));
    }

    function _addForm ($sRedirectUrl) {

        bx_import ('FormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {

            $sStatus = $this->_oDb->getParam($this->_sPrefix.'_autoapproval') == 'on' || $this->isAdmin() ? 'approved' : 'pending';

            $sStatus = (!$oForm->getCleanValue('publish')) && $this->isAdmin() ? 'draft' : $sStatus;
  
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
            $aValsAdd[$this->_oDb->_sFieldAuthorId] = $this->_iProfileId;

            $iEntryId = $oForm->insert ($aValsAdd);

            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 

                $oForm->processMedia($iEntryId, $this->_iProfileId);

                $aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin());
                $this->onEventCreate($iEntryId, $sStatus, $aDataEntry);
                if (!$sRedirectUrl)
                    $sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else {
            
            echo $oForm->getCode ();

        }
    }

    function _actionEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
        $GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
            _t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
            $aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
            $sTitle => '',
        ));

        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        bx_import ('FormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormEdit';
        $oForm = new $sClass ($this, $aDataEntry[$this->_oDb->_sFieldAuthorId], $iEntryId, $aDataEntry);
        if (isset($aDataEntry[$this->_oDb->_sFieldJoinConfirmation]))
            $aDataEntry[$this->_oDb->_sFieldJoinConfirmation] = (int)$aDataEntry[$this->_oDb->_sFieldJoinConfirmation];
        
        $oForm->initChecker($aDataEntry);

        if ($oForm->isSubmittedAndValid ()) {

            $sStatus = $this->_oDb->getParam($this->_sPrefix . '_autoapproval') == 'on' || $this->isAdmin() ? 'approved' : 'pending';

            $sStatus = (!$oForm->getCleanValue('publish')) && $this->isAdmin() ? 'draft' : $sStatus;
 
            $aValsAdd = array ($this->_oDb->_sFieldStatus => $sStatus);
            if ($oForm->update ($iEntryId, $aValsAdd)) {

                $oForm->processMedia($iEntryId, $this->_iProfileId);

                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventChanged ($iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode($sTitle);
    }

    function actionEdit ($iEntryId) {
        parent::_actionEdit ($iEntryId, _t('_modzzz_notices_page_title_edit'));
    }

    function actionDelete ($iEntryId) {
        parent::_actionDelete ($iEntryId, _t('_modzzz_notices_msg_notice_was_deleted'));
    }

    function actionMarkFeatured ($iEntryId) {
        parent::_actionMarkFeatured ($iEntryId, _t('_modzzz_notices_msg_added_to_featured'), _t('_modzzz_notices_msg_removed_from_featured'));
    }
 
    function actionSharePopup ($iEntryId) {
        parent::_actionSharePopup ($iEntryId, _t('_modzzz_notices_caption_share_notice'));
    }
 
    function actionTags() {
        parent::_actionTags (_t('_modzzz_notices_page_title_tags'));
    }    
  
    // ================================== external actions

    /**
     * Homepage block with different notices
     * @return html to display on homepage in a block
     */     
    function serviceHomepage ($sType='travel') {
 
        if (!$this->_oDb->isAnyPublicContent()){ 
			return '';
        } 
        bx_import ('PageMain', $this->_aModule);
        $o = new BxNoticesPageMain ($this);
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';
        
		$this->_oTemplate->addCss(array('unit.css'));

        $sDefaultHomepageTab = $this->_oDb->getParam('modzzz_notices_homepage_default_tab').'_'.$sType;
        $sBrowseMode = $sDefaultHomepageTab;
        switch ($_GET['modzzz_notices_filter']) {            
            case 'featured_'.$sType:
            case 'recent_'.$sType:
            case 'top_'.$sType:
            case 'popular_'.$sType:
            case $sDefaultHomepageTab:            
                $sBrowseMode = $_GET['modzzz_notices_filter'];
                break;
        }

        return $o->ajaxBrowse(
            $sBrowseMode,
            $this->_oDb->getParam('modzzz_notices_perpage_homepage'), 
            array(
                _t('_modzzz_notices_tab_featured') => array('href' => BX_DOL_URL_ROOT . '?modzzz_notices_filter=featured_'.$sType, 'active' => 'featured_'.$sType == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_notices_tab_recent') => array('href' => BX_DOL_URL_ROOT . '?modzzz_notices_filter=recent_'.$sType, 'active' => 'recent_'.$sType == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_notices_tab_top') => array('href' => BX_DOL_URL_ROOT . '?modzzz_notices_filter=top_'.$sType, 'active' => 'top_'.$sType == $sBrowseMode, 'dynamic' => true),
                _t('_modzzz_notices_tab_popular') => array('href' => BX_DOL_URL_ROOT . '?modzzz_notices_filter=popular_'.$sType, 'active' => 'popular_'.$sType == $sBrowseMode, 'dynamic' => true),
            )
        );
    }


    /**
     * Profile block with user's notices
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceAccountPage () {
        $iProfileId = (int)$this->_iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxNoticesPageMain ($this);        
        $o->sUrlStart = BX_DOL_URL_ROOT .  'member.php?';
        
		$this->_oTemplate->addCss(array('unit.css'));

        return $o->ajaxBrowse(
            'user', 
            $this->_oDb->getParam('modzzz_notices_perpage_profile'), 
            array(),
            getNickName($aProfile['ID']),
            true,
            false 
        );
    }

    /**
     * Profile block with user's notices
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceProfileBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxNoticesPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';
        
		$this->_oTemplate->addCss(array('unit.css'));

        return $o->ajaxBrowse(
            'user', 
            $this->_oDb->getParam('modzzz_notices_perpage_profile'), 
            array(),
            $aProfile['NickName'],
            true,
            false 
        );
    }

    function serviceGetMemberMenuItem () {
        parent::_serviceGetMemberMenuItem (_t('_modzzz_notices'), _t('_modzzz_notices'), 'notices.png');
    }

    function serviceGetWallPost ($aEvent) {
         return parent::_serviceGetWallPost ($aEvent, _t('_modzzz_notices_wall_object'), _t('_modzzz_notices_wall_added_new'));
    }

    function serviceGetSpyPost($sAction, $iObjectId = 0, $iSenderId = 0, $aExtraParams = array()) {
        return parent::_serviceGetSpyPost($sAction, $iObjectId, $iSenderId, $aExtraParams, array(
            'add' => '_modzzz_notices_spy_post',
            'change' => '_modzzz_notices_spy_post_change', 
            'rate' => '_modzzz_notices_spy_rate',
            'commentPost' => '_modzzz_notices_spy_comment',
        ));
    }

    function serviceGetSubscriptionParams ($sAction, $iEntryId) {

        $a = array (
            'change' => _t('_modzzz_notices_sbs_change'),
            'commentPost' => _t('_modzzz_notices_sbs_comment'),
            'rate' => _t('_modzzz_notices_sbs_rate'), 
        );

        return parent::_serviceGetSubscriptionParams ($sAction, $iEntryId, $a);
    }

    // ================================== admin actions

    function actionAdministration ($sUrl = '') {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $this->_oTemplate->pageStart();

        $aMenu = array(
            'pending_approval' => array(
                'title' => _t('_modzzz_notices_menu_admin_pending_approval'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/pending_approval', 
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(false)),
            ),
            'pending_publish' => array(
                'title' => _t('_modzzz_notices_menu_admin_pending_publish'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/pending_publish', 
                '_func' => array ('name' => 'actionAdministrationPublish', 'params' => array()),
            ), 
            'admin_entries' => array(
                'title' => _t('_modzzz_notices_menu_admin_entries'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/admin_entries',
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(true)),
            ),            
            'create' => array(
                'title' => _t('_modzzz_notices_menu_admin_add_entry'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/create',
                '_func' => array ('name' => 'actionAdministrationCreateEntry', 'params' => array()),
            ),
            'settings' => array(
                'title' => _t('_modzzz_notices_menu_admin_settings'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/settings',
                '_func' => array ('name' => 'actionAdministrationSettings', 'params' => array()),
            ),
        );

        if (empty($aMenu[$sUrl]))
            $sUrl = 'pending_approval';

        $aMenu[$sUrl]['active'] = 1;
        $sContent = call_user_func_array (array($this, $aMenu[$sUrl]['_func']['name']), $aMenu[$sUrl]['_func']['params']);

        echo $this->_oTemplate->adminBlock ($sContent, _t('_modzzz_notices_page_title_administration'), $aMenu);
        $this->_oTemplate->addCssAdmin ('admin.css');
        $this->_oTemplate->addCssAdmin ('unit.css');
        $this->_oTemplate->addCssAdmin ('main.css');
        $this->_oTemplate->addCssAdmin ('forms_extra.css'); 
        $this->_oTemplate->addCssAdmin ('forms_adv.css');        
        $this->_oTemplate->pageCodeAdmin (_t('_modzzz_notices_page_title_administration'));
    }

    function actionAdministrationSettings () {
        return parent::_actionAdministrationSettings ('Notices');
    }

    function actionAdministrationManage ($isAdminEntries = false) {
        return parent::_actionAdministrationManage ($isAdminEntries, '_modzzz_notices_admin_delete', '_modzzz_notices_admin_activate');
    }
  
    function actionAdministrationPublish () {
		$sKeyBtnDelete = '_modzzz_notices_admin_delete';
		$sKeyBtnPublish = '_modzzz_notices_admin_publish';

        if ($_POST['action_publish'] && is_array($_POST['entry'])) {

            foreach ($_POST['entry'] as $iId) {
                if ($this->_oDb->publishEntry($iId)) {
                    $this->onEventChanged ($iId, 'publish');
                }
            }

        } elseif ($_POST['action_delete'] && is_array($_POST['entry'])) {

            foreach ($_POST['entry'] as $iId) {

                $aDataEntry = $this->_oDb->getEntryById($iId);
                if (!$this->isAllowedDelete($aDataEntry)) 
                    continue;

                if ($this->_oDb->deleteEntryByIdAndOwner($iId, 0, $this->isAdmin())) {
                    $this->onEventDeleted ($iId);
                }
            }
        }
 
		$sContent = $this->_manageEntries ('draft', '', true, 'bx_twig_admin_form', array(
			'action_publish' => $sKeyBtnPublish,
			'action_delete' => $sKeyBtnDelete,
		));
    
        return $sContent;
    }



    // ================================== events
 

 
    // ================================== permissions
    
    function isAllowedView ($aDataEntry, $isPerformAction = false) {

        // admin and owner always have access
        if ($this->isAdmin() || $aDataEntry['author_id'] == $this->_iProfileId) 
            return true;

        // check admin acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_VIEW_NOTICE, $isPerformAction);
        if ($aCheck[CHECK_ACTION_RESULT] != CHECK_ACTION_RESULT_ALLOWED)
            return false;

        // check user notice 
	    $isAllowed = $this->_oPrivacy->check('view_notice', $aDataEntry['id'], $this->_iProfileId); 
       
        return $isAllowed && $this->_isAllowedViewByMembership ($aDataEntry);
    }

    function _isAllowedViewByMembership (&$aDataEntry) { 
        if (!$aDataEntry['notice_membership_filter']) return true;

        require_once(BX_DIRECTORY_PATH_INC . 'membership_levels.inc.php');
        $aMemebrshipInfo = getMemberMembershipInfo($this->_iProfileId);
 
		$aAllowed = explode(';', $aDataEntry['notice_membership_filter']);

		foreach($aAllowed as $aEachFilter){
			if($aMemebrshipInfo['DateExpires']){ 
				if($aEachFilter == $aMemebrshipInfo['ID'] && $aMemebrshipInfo['DateStarts'] < time() && $aMemebrshipInfo['DateExpires'] > time())
					return true;
			}else{
				if($aEachFilter == $aMemebrshipInfo['ID'] && $aMemebrshipInfo['DateStarts'] < time())
					return true; 
			}
		}

		return false;
    }
 
    function isAllowedBrowse ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_BROWSE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedSearch ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_SEARCH, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedAdd ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (!$GLOBALS['logged']['member']) 
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_ADD_NOTICE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedEdit ($aDataEntry, $isPerformAction = false) {

        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;

        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_EDIT_ANY_NOTICE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedMarkAsFeatured ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_NOTICES_MARK_AS_FEATURED, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }
  
    function isAllowedDelete (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_DELETE_ANY_NOTICE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }     
  
    function isAllowedShare (&$aDataEntry) {
        return true;
    }
 

    function isAllowedRate(&$aDataEntry) {        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('rate', $aDataEntry['id'], $this->_iProfileId);        
    }

    function isAllowedComments(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('comment', $aDataEntry['id'], $this->_iProfileId);
    }
  
    function isAllowedUploadPhotos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForImages())
            return false;
        return $this->_oPrivacy->check('upload_photos', $aDataEntry['ID'], $this->_iProfileId);
    }

    function isAllowedUploadVideos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForVideos())
            return false;                
        return $this->_oPrivacy->check('upload_videos', $aDataEntry['ID'], $this->_iProfileId);
    }

    function isAllowedUploadSounds(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForSounds())
            return false;                        
        return $this->_oPrivacy->check('upload_sounds', $aDataEntry['ID'], $this->_iProfileId);
    }

    function isAllowedUploadFiles(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForFiles())
            return false;                        
        return $this->_oPrivacy->check('upload_files', $aDataEntry['ID'], $this->_iProfileId);
    }

    function isAllowedCreatorCommentsDeleteAndEdit (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) return true;        
        if (!$GLOBALS['logged']['member'] || $aDataEntry['ResponsibleID'] != $this->_iProfileId)
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_NOTICES_COMMENTS_DELETE_AND_EDIT, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedManageAdmins($aDataEntry) {
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))
            return true;
        return false;
    }
   
	function isPermalinkEnabled() {
		$bEnabled = isset($this->_isPermalinkEnabled) ? $this->_isPermalinkEnabled : ($this->_isPermalinkEnabled = (getParam('permalinks_notices') == 'on'));
		 
        return $bEnabled;
    }


    function _defineActions () {
        defineMembershipActions(array('notices view notice', 'notices browse', 'notices search', 'notices add notice', 'notices comments delete and edit', 'notices edit any notice', 'notices delete any notice', 'notices mark as featured', 'notices approve notices' ));
    }

    function _browseMy (&$aProfile) {        
        parent::_browseMy ($aProfile, _t('_modzzz_notices_page_title_my_notices'));
    } 
	
    function onEventCreate ($iEntryId, $sStatus, $aDataEntry = array()) {
  
		if ('approved' == $sStatus) {
            $this->reparseTags ($iEntryId);
         }
 		$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }

    function getTagLinks($sTagList, $sType = 'tag', $sDivider = ' ') {
        if (strlen($sTagList)) {
            $aTags = explode($sDivider, $sTagList);
            foreach ($aTags as $iKey => $sValue) {
                $sValue   = trim($sValue, ','); 
                $aRes[$sValue] = $sValue;
            }
        }
        return $aRes;
    }

    function parseTags($s)
    {
        return $this->_parseAnything($s, ',', BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/tag/');
    }
  
    function _parseAnything($s, $sDiv, $sLinkStart, $sClassName = '')
    {
        $sRet = '';
        $a = explode ($sDiv, $s);
        $sClass = $sClassName ? 'class="'.$sClassName.'"' : '';
        
        foreach ($a as $sName)
            $sRet .= '<a '.$sClass.' href="' . $sLinkStart . urlencode(title2uri($sName)) . '">'.$sName.'</a>&#160';
        
        return $sRet;
    }

    function isEntryAdmin($aDataEntry, $iIdProfile = 0) {
        if (!$iIdProfile)
            $iIdProfile = $this->_iProfileId;
        return ($this->isAdmin() || $aDataEntry['author_id'] == $iIdProfile);
    }
 

}

?>
